package com.syni.mdd.sjb.community.base.auth;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.syni.mdd.sjb.common.component.mybatis.common.entity.DxshAppUserInfo;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxAdmin;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

;

/**
 * @className JwtTokenUtil
 * @description TOO
 * @Author cfx
 * @DATE 2020/4/10 9:39
 * @VERSION 1.0
 **/
@Component
public class JwtTokenUtils {
    public static ThreadLocal<BackPcAuthUserBo> backPcAuthUserBoThreadLocal = new ThreadLocal<>();
    private static Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
    private int VALID_TIME = 30; // token有效期(秒)
    public static final int TOKEN_ERROR = -1; // 非法
    public static final int TOKEN_OVERDUE = 0; // 无效
    public static final int TOKEN_SUCCESS = 1; // 验证成功

    public String getToken(SjbQywxAdmin sjbQywxAdmin) {
        Date expireTime = DateTimeUtils.addDay(new Date(),VALID_TIME);
        BackPcAuthUserBo authUserBo = new BackPcAuthUserBo(sjbQywxAdmin.getId(),sjbQywxAdmin.getUserid(),sjbQywxAdmin.getCorpid());
        String token = JWT.create().withAudience(authUserBo.toString()).withExpiresAt(expireTime)
                .sign(Algorithm.HMAC256(WebUtils.MD5(sjbQywxAdmin.getId() + sjbQywxAdmin.getUserid())));
        return token;
    }

    public String getPostBindTokenToken(SjbQywxAdmin sjbQywxAdmin, DxshAppUserInfo dxshAppUserInfo) {
        //String HMAC256Value =
        if(dxshAppUserInfo != null){

        }
        Date expireTime = DateTimeUtils.addDay(new Date(),VALID_TIME);
        BackPcAuthUserBo authUserBo = new BackPcAuthUserBo(sjbQywxAdmin.getId(),sjbQywxAdmin.getUserid(),sjbQywxAdmin.getCorpid(),dxshAppUserInfo);
        String token = JWT.create().withAudience(authUserBo.toString()).withExpiresAt(expireTime)
                .sign(Algorithm.HMAC256(WebUtils.MD5(sjbQywxAdmin.getId() + sjbQywxAdmin.getUserid())));
        return token;
    }

    /**
     * 校验token的有效性
     * @param token
     * @return
     */
    public int checkToken(String token) {
        if (token == null) {
            return TOKEN_ERROR;
        }
        try{
            List<String> tokenData = JWT.decode(token).getAudience();
            if(!(tokenData.size() > 0)) {
                return TOKEN_ERROR;
            }
            //检查token是否无效
            String userData = tokenData.get(0);
            BackPcAuthUserBo backPcAuthUserBo = JSON.parseObject(userData, BackPcAuthUserBo.class);
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(WebUtils.MD5( backPcAuthUserBo.getQxwxAdminId() + backPcAuthUserBo.getQxyxUserid()))).build();
            jwtVerifier.verify(token);
            backPcAuthUserBoThreadLocal.set(backPcAuthUserBo);
            return TOKEN_SUCCESS;
        }catch (Exception e) {
            logger.info(e.toString());
        }
        return TOKEN_ERROR;
    }

    public String verifyToken(String token) {
        if(StringUtils.isNotBlank(token)) {
            try {
                List<String> tokenData = JWT.decode(token).getAudience();
                //检查token是否无效
                String data = tokenData.get(0);
                return data;
            } catch (Exception e) {
                logger.info(e.toString());
            }
        }
        return "";
    }
}
